package com.example.education.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

@WebFilter(urlPatterns = {"/interface/*", "/", "/page/loginPage", "/page/registerPage"}, filterName = "loginFilter"
        , initParams = {@WebInitParam(name = "passPath", value = "/,/interface/home,/page/loginPage,/page/registerPage," +
        "/interface/user/login,/interface/user/register")})
public class LoginFilter implements Filter {
    private static Set<String> skipPath = new ConcurrentSkipListSet<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String passPaths = filterConfig.getInitParameter("passPath");
        String[] passPathArr = passPaths.split(",");
        for (String path : passPathArr) {
            skipPath.add(path);
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = ((HttpServletRequest) servletRequest);
        String contextPath = request.getRequestURI();
        if (skipPath.contains(contextPath)|| request.getSession().getAttribute("user") != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            ((HttpServletResponse) servletResponse).sendRedirect("/page/loginPage");
        }
    }

    @Override
    public void destroy() {

    }
}
